package cn.swenty.backstage.framework.common.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * 
 * @author 王永明
 * @since Jul 8, 2009 5:15:58 PM
 */
public class CollectionUtil {

	/**
	 * 从列表里面随机取出一些对象
	 * 
	 * @param list 数据来源
	 * @param count 获取个数
	 */
	public static List getRandom(List list, int count) {
		List randoms = new ArrayList();
		int size = list.size();
		Random r = new Random();
		//从list里面随机取一个,移到randoms里面
		for (int i = size; i > (size - count); i--) {
			int no = r.nextInt(i);
			randoms.add(list.get(no));
			list.remove(list.get(no));
		}
		return randoms;

	}
	
	/**从列表里随机获取一个对象*/
	public static Object getRandom(List list){
		int size = list.size();
		Random r = new Random();
		return list.get(r.nextInt(size));

	}
	
	public static boolean hasObject(List list,Object o){
		
		for(Object oo:list){
			if(oo.equals(o)){
				return true;
			}
		}
		return false;
	}
	
	
	/**
	 *
	 * 排序*/
	public static List sort(List list,final String... field){
		Collections.sort(list, new MyComparator(field));
		return list;
	}
	
	public static class MyComparator implements Comparator{
		public String[] compareField;
		public MyComparator(String[] compareField){
			this.compareField=compareField;
		}
		
		public int compare(Object o1, Object o2) {
			int result=0;
			for(int i=0;i<compareField.length;i++){
				Object obj1=BeanUtil.getValue(o1, compareField[i]);
				Object obj2=BeanUtil.getValue(o2, compareField[i]);
				if(obj1==null||obj2==null){
					break;
				}else if(obj1 instanceof Date){
					Date d1=(Date)obj1;
					Date d2=(Date)obj2;
					result= (int)(d1.getTime()-d2.getTime());
				}else if(obj1 instanceof Integer){
					Integer d1=(Integer)obj1;
					Integer d2=(Integer)obj2;
					result=(d1-d2);
				}else{
					result= obj1.toString().compareTo(obj2.toString());
				}	
	
				if(result!=0){
					break;
				}
			}
			return result;
		}
		
	}
	
	public static String join(Collection coll,String split){
		String str = "";
		Iterator<Object> iterator = coll.iterator();
		while(iterator.hasNext()){
			str += iterator.next()+split;
		}
		return str;
	}
	
	public static void main(String[] args) {
		System.out.println("2".compareTo("3".toString()));
	}
	

	/**将一个集合的某个属性放到String*/
	public static String[] toString(Collection coll,String property){
		String[] re=new String[coll.size()];
		int i=0;
		for(Object o:coll){
			Object str=BeanUtil.getValue(o, property);
			if(str==null){
				throw new RuntimeException(o+"的属性"+property+"为空!");
			}
			re[i]=str.toString();
			i++;
		}
		return re;
	}
	
	public static List createList(Object obj){
		List list=new ArrayList();
		list.add(obj);
		return list;
	}

	
}
